package top.codedance.iotp.tools.terminal.wser;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.iot.sdk.SimpleClientMessageAdapter;
import top.codedance.iotp.iot.sdk.WsSimpleClient;
import top.codedance.iotp.iot.sdk.po.async.WsSystemExecCommandParam;
import top.codedance.iotp.iot.sdk.po.async.WsSystemPowershellParam;
import top.codedance.iotp.tools.terminal.bean.WebsocketConnectParam;
import top.codedance.iotp.tools.terminal.comer.CallOwner;

import java.nio.charset.StandardCharsets;

public class WsClient {
    private CallOwner owner;
    private WebsocketConnectParam websocketConnectParam;
    private WsSimpleClient  wsClient;

    public WsClient(CallOwner owner, WebsocketConnectParam websocketConnectParam){
        this.owner = owner;
        this.websocketConnectParam = websocketConnectParam;
        connect();
    }

    private void connect(){
        wsClient = new WsSimpleClient(websocketConnectParam.getUrl() + "/services/system", websocketConnectParam.getUsername(), websocketConnectParam.getPassword(), websocketConnectParam.getDeviceId());
        wsClient.addListener(new SimpleClientMessageAdapter() {
            @Override
            public void call(String body) {
                JSONObject jo = JSON.parseObject(body);
                appendResult(jo.getString("data"));
            }

            @Override
            public void error(String error) {
                appendError(error);
            }

            @Override
            public void close() {
                appendResult("WS is closed.");
            }
        });
        wsClient.send(new WsSystemPowershellParam(false));
        wsClient.waiting(1);
    }

    public boolean isOpen(){
        return wsClient.isRunning();
    }

    public void close(){
        wsClient.close();
    }

    public void send(String data){
        wsClient.send(new WsSystemExecCommandParam(data));
    }

    public void send(byte[] data){
        send(new String(data, StandardCharsets.UTF_8));
    }

    public void appendResult(String data){
        owner.appendResult(data);
    }

    public void appendError(String data){
        owner.appendError(data);
    }

    public void setOwner(CallOwner owner) {
        this.owner = owner;
    }

    public void waiting(long second){
        wsClient.waiting(second);
    }

    public void reconnect(){
        wsClient.reconnect();
    }
}
